<template>
	<div class="order">
		<el-button type="primary" plain @click="toBack">返回</el-button>
		<el-button v-if="generateContract()" type="primary" @click="generate" v-debounce>
			生成合同
		</el-button>
		<el-button v-if="isReceipt" type="primary" @click="receipt" v-debounce>
			生成单据
		</el-button>
		<h3>订单详情</h3>
		<el-form inline label-position="top" :model="order" :rules="rules" ref="ruleForm">
			<el-form-item label="订单流水" v-if="order.id !== null">
				<el-input v-model="order.sn" placeholder="订单流水" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="订单类型">
				<el-select :value="order.orderType" :disabled="isAdd" @change="orderTypeChange">
					<el-option label="开销开单" :value="1"></el-option>
					<el-option label="签订合同" :value="2"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="下单客户" prop="clientsId">
				<el-input :value="order.name" placeholder="选择客户" @focus="clientsDialogShow" readonly :disabled="isAdd">
				</el-input>
			</el-form-item>
			<el-form-item label="联系电话">
				<el-input v-model="order.phone" placeholder="联系电话" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="公司名称">
				<el-input v-model="order.company" placeholder="公司名称" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="交货地点">
				<el-input v-model="order.address" placeholder="交货地点" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="交货时间" prop="deliveryTime" key="deliveryTime">
				<el-date-picker v-model="order.deliveryTime" type="date" placeholder="选择日期" :readonly="isAdd"
					style="width: 100%;" @change="dateChange($event, 'deliveryTime')">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="总金额">
				<el-input v-model="order.transactionAmount" placeholder="总金额" type="number" step="0.01" @input="check"
					@change="change" :readonly="isAdd">
				</el-input>
			</el-form-item>
			<el-form-item v-if="order.orderType === 2" label="定金" prop="deposit" key="deposit">
				<el-input v-model="order.deposit" placeholder="定金" type="number" step="0.01" @input="depositCheck"
					@change="depositChange" :readonly="isAdd">
				</el-input>
			</el-form-item>
			<el-form-item v-if="order.orderType === 2" label="首付款" prop="downPayment" key="downPayment">
				<el-input v-model="order.downPayment" placeholder="首付款" type="number" step="0.01"
					@input="downPaymentCheck" @change="depositChange" :readonly="isAdd">
				</el-input>
			</el-form-item>
			<el-form-item v-show="order.orderType === 2" label="尾款">
				<el-input v-model="balancePayment" placeholder="尾款" type="number" step="0.01" readonly>
				</el-input>
			</el-form-item>
			<el-form-item v-show="order.orderType === 2" label="付款方式">
				<el-select v-model="order.paymentMethod" :disabled="isAdd" @change="paymentMethodChange">
					<el-option label="全款" :value="0"></el-option>
					<el-option v-for="(i, index) in byStages" :label="`分${i}期`" :value="i" :key="index"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item v-if="order.orderType === 2 && order.paymentMethod > 0" label="每期应还">
				<el-input v-model="order.phaseAmount" placeholder="每期应还" type="number" step="0.01" readonly>
				</el-input>
			</el-form-item>
			<el-form-item v-if="order.orderType === 2 && order.paymentMethod > 0" label="末期应还">
				<el-input v-model="order.lastAmount" placeholder="末期应还" type="number" step="0.01" readonly>
				</el-input>
			</el-form-item>
			<el-form-item v-if="isAdd && order.orderType === 2" label="每月还款日">
				<el-input :value="`${order.repaymentDate} 号`" readonly></el-input>
			</el-form-item>
			<el-form-item label="付款类型">
				<el-select v-model="order.paymentType" :disabled="isAdd">
					<el-option label="先发后付" :value="0"></el-option>
					<el-option label="先付后发" :value="1"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item v-if="order.orderType === 2" label="签订地点" prop="place" key="place">
				<el-input v-model="order.place" placeholder="签订地点" :readonly="isAdd">
				</el-input>
			</el-form-item>
			<el-form-item v-if="order.orderType === 2" label="还款截止日期" prop="deadline" key="deadline">
				<el-date-picker v-model="order.deadline" type="date" placeholder="选择日期" :readonly="isAdd"
					style="width: 100%;" @change="dateChange($event, 'deadline')">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="业务员" prop="userId">
				<el-select v-model="order.userId" filterable remote placeholder="按名字搜索" @change="selectUserChange"
					:remote-method="getUserList" :loading="selectLoading" @focus="getUserList('')">
					<el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="售后员">
				<el-select v-model="order.afterSaleId" filterable remote placeholder="按名字或工号搜索"
					@change="selectAfterSaleChange" :remote-method="getAfterSaleList" :loading="selectLoading"
					:disabled="afterSaleDisabled()" @focus="getAfterSaleList('')">
					<el-option v-for="item in afterSaleList" :key="item.id" :label="item.nickName" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item v-if="order.orderType === 2" label="客户身份证号" prop="clientsIdCard" key="clientsIdCard">
				<el-input v-model="order.clientsIdCard" placeholder="客户身份证号" :readonly="isAdd">
				</el-input>
			</el-form-item>
			<el-form-item label="备注">
				<el-input v-model="order.remark" placeholder="备注" :readonly="isAdd">
				</el-input>
			</el-form-item>
			<el-form-item v-show="order.orderType === 2" label="身份证复印件照片">
				<div style="display: flex;">
					<div class="order-img-div" v-for="(item, index) in copyOfIdCardShowList" :key="index"
						style="position: relative;margin-right: 10px;">
						<el-image :src="item" class="htimg" :preview-src-list="copyOfIdCardShowList">
						</el-image>
						<i class="el-icon-close hover-icon" @click="deleteImg(0, index)"></i>
					</div>
					<img :src="imgUrl" class="htimg" @click="selectFile(0)" v-if="copyOfIdCardShowList.length < 2" />
				</div>
			</el-form-item>
			<el-form-item label="验收单">
				<div style="display: flex;">
					<div class="order-img-div" v-for="(item, index) in receiptShowList" :key="index"
						style="position: relative;margin-right: 10px;">
						<el-image :src="item" class="htimg" :preview-src-list="receiptShowList">
						</el-image>
						<i class="el-icon-close hover-icon" @click="deleteImg(1, index)"></i>
					</div>
					<img :src="imgUrl" class="htimg" @click="selectFile(1)" v-if="receiptShowList.length < 3" />
				</div>
			</el-form-item>
			<el-form-item label="物流信息">
				<div style="display: flex;">
					<div class="order-img-div" v-for="(item, index) in logisticsInformationShowList" :key="index"
						style="position: relative;margin-right: 10px;">
						<el-image :src="item" class="htimg" :preview-src-list="logisticsInformationShowList">
						</el-image>
						<i class="el-icon-close hover-icon" @click="deleteImg(2, index)"></i>
					</div>
					<img :src="imgUrl" class="htimg" @click="selectFile(2)"
						v-if="logisticsInformationShowList.length < 3" />
				</div>
			</el-form-item>
			<el-form-item label="签订合同/开销单">
				<div style="display: flex;">
					<div class="order-img-div" v-for="(item, index) in contractShowList" :key="index"
						style="position: relative;margin-right: 10px;">
						<el-image :src="item" class="htimg" :preview-src-list="contractShowList">
						</el-image>
						<i class="el-icon-close hover-icon" @click="deleteImg(3, index)"></i>
					</div>
					<img :src="imgUrl" class="htimg" @click="selectFile(3)" v-if="contractShowList.length < 3" />
				</div>
			</el-form-item>
			<el-form-item label="产品列表" style="width: 100%">
				<div>
					<el-button type="text" @click="devicesDialogShow" v-if="!isAdd">
						添加产品
					</el-button>
					<label style="float: right;">
						{{ `总金额：${order.transactionAmount}` }}
					</label>
				</div>
				<el-table :data="order.goodsList" border style="width: 100%" :max-height="400">
					<el-table-column prop="i" fixed="left" label="序号" width="50">
					</el-table-column>
					<el-table-column label="图片" width="125">
						<template slot-scope="scope">
							<el-image :src="READ_IMG_URL + scope.row.image" style="width: 100px; height: 100px;"
								:preview-src-list="new Array(READ_IMG_URL + scope.row.image)">
							</el-image>
						</template>
					</el-table-column>
					<el-table-column prop="isProduct" label="产品类型" width="80">
						<template slot-scope="scope">
							<el-tag>{{ productTypeList.find(item => item.id ==
								scope.row.isProduct)?.productType}}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="partName" label="产品名称" fit>
					</el-table-column>
					<el-table-column prop="model" label="产品型号" fit>
					</el-table-column>
					<el-table-column prop="devicesDescribe" label="产品描述" fit>
					</el-table-column>
					<el-table-column prop="remark" label="备注" fit>
					</el-table-column>
					<el-table-column prop="price" label="销售单价" width="80">
					</el-table-column>
					<el-table-column prop="goodsCount" label="卖出数量" width="110">
						<template slot-scope="scope">
							<el-input v-model="scope.row.goodsCount" type="number" placeholder="卖出数量" :readonly="isAdd"
								@input="inputCheck($event, scope.row)" @change="countChange($event, scope.row)">
							</el-input>
							<span v-if="scope.row.inventory" style="color: red;">
								库存不足
							</span>
						</template>
					</el-table-column>
					<el-table-column prop="totalAmount" label="总计" width="80">
					</el-table-column>
					<el-table-column label="操作" width="55" v-if="!isAdd">
						<template slot-scope="scope">
							<el-button type="text" @click="deleteParts(scope.row)">
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
			<div v-show="!isAdd">
				<el-button @click="resetForm('ruleForm')">重置</el-button>
				<el-button type="primary" @click="submitForm('ruleForm')" v-debounce>
					提交
				</el-button>
			</div>
		</el-form>

		<!-- 选择客户 -->
		<el-dialog style="margin-top:0" :visible.sync="clientsShow" width="75%" title="选择客户">
			<div style=" width: 100%;display: flex;justify-content: flex-end;margin-bottom: 10px;">
				<!-- 条件查询 -->
				<div>
					<el-input v-model="clientForm.name" placeholder="按公司,姓名,手机号,地址搜索" clearable @change="getClientList"
						style="width: 400px;">
					</el-input>
					<!-- 客户状态 -->
					<el-select v-model="clientForm.type" style="width: 110px;margin-left: 10px;"
						@change="getClientList">
						<el-option label="全部客户" :value="null"></el-option>
						<el-option label="成交客户" :value="0"></el-option>
						<el-option label="意向客户" :value="1"></el-option>
						<el-option label="纸箱厂客户" :value="2"></el-option>
						<el-option label="失信客户" :value="3"></el-option>
					</el-select>
				</div>
			</div>
			<el-table :data="clientList" v-loading="loading" border style="width: 100%" :max-height="430">
				<el-table-column prop="i" label="序号" width="50">
				</el-table-column>
				<el-table-column prop="company" label="公司名称" fit>
				</el-table-column>
				<el-table-column prop="name" label="客户姓名" fit>
				</el-table-column>
				<el-table-column prop="phone" label="手机号" fit>
				</el-table-column>
				<el-table-column prop="address" label="地址" fit>
				</el-table-column>
				<!--  0成交客户，1意向客户，2潜在客户，3失信客户 -->
				<el-table-column prop="type" label="客户状态" width="100">
					<template slot-scope="scope">
						<el-tag type="success" v-if="typeInfo(scope.row.type) == '成交客户'">
							{{ typeInfo(scope.row.type) }}</el-tag>
						<el-tag type="warning" v-if="typeInfo(scope.row.type) == '意向客户'">
							{{ typeInfo(scope.row.type) }}</el-tag>
						<el-tag type="info" v-if="typeInfo(scope.row.type) == '潜在客户'">
							{{ typeInfo(scope.row.type) }}</el-tag>
						<el-tag type="danger" v-if="typeInfo(scope.row.type) == '失信客户'">
							{{ typeInfo(scope.row.type) }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column width="75" label="操作">
					<template slot-scope="scope">
						<el-button type="text" @click="selectClientChange(scope.row)">选择</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination background :current-page="clientForm.currentPage" :page-size="clientForm.pageSize"
				:total="clientForm.total" :page-sizes="[20, 50, 100]" @size-change="clientFormSizeChange"
				@current-change="clientFormCurrentChange" layout="total, sizes, prev, pager, next, jumper">
			</el-pagination>
		</el-dialog>
		<!-- 选择产品 -->
		<el-dialog style="margin-top:0" :visible.sync="devicesShow" width="85%" title="选择产品">
			<div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
				<div>
					<el-button type="primary" @click="confirmParts">确定</el-button>
				</div>
				<!-- 条件查询 -->
				<div style="display: flex;">
					<el-input v-model="form.partName" placeholder="按名称型号搜索" clearable @change="getDevicesList">
					</el-input>
					<el-select v-model="form.warehouseType" @change="getDevicesList"
						style="width: 200px; margin-left: 10px">
						<el-option label="全部" :value="void 0"></el-option>
						<el-option v-for="item in productlibraryList" :label="item.libraryName" :key="item.id"
							:value="item.id"></el-option>
					</el-select>
					<el-select v-model="form.isProduct" @change="getDevicesList"
						style="width: 200px; margin-left: 10px">
						<el-option label="全部" :value="void 0"></el-option>
						<el-option v-for="item in typeListComputed" :label="item.productType" :key="item.id"
							:value="item.id"></el-option>
					</el-select>
				</div>
			</div>
			<el-table :data="devicesList" v-loading="loading" border style="width: 100%" :max-height="430"
				:row-key="(row) => row.id" @selection-change="handleSelectionChange" ref="multipleTable">
				<el-table-column type="selection" :reserve-selection="true" width="40">
				</el-table-column>
				<el-table-column prop="i" label="序号" width="60">
				</el-table-column>
				<el-table-column label="产品图片" width="125">
					<template slot-scope="item">
						<el-image style="width: 100px; height: 100px" :src="READ_IMG_URL + item.row.image"
							:preview-src-list="new Array(READ_IMG_URL + item.row.image)">
						</el-image>
					</template>
				</el-table-column>
				<el-table-column prop="isProduct" label="产品类型" width="80">
					<template slot-scope="scope">
						<el-tag>{{ productTypeList.find(item => item.id == scope.row.isProduct)?.productType }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="partName" label="产品名称" fit>
				</el-table-column>
				<el-table-column prop="model" label="产品型号" fit>
				</el-table-column>
				<el-table-column prop="devicesDescribe" label="产品描述" fit>
				</el-table-column>
				<el-table-column prop="remark" label="备注" fit>
				</el-table-column>
				<el-table-column prop="price" label="销售价格" width="100">
				</el-table-column>
				<el-table-column prop="count" label="库存数量" width="100">
				</el-table-column>
			</el-table>
			<el-pagination background :current-page="form.currentPage" :page-size="form.pageSize" :total="form.total"
				:page-sizes="[20, 50, 100]" @size-change="formSizeChange" @current-change="formCurrentChange"
				layout="total, sizes, prev, pager, next, jumper">
			</el-pagination>
		</el-dialog>

		<!-- 订单账单 -->
		<div style="padding-bottom: 20px;">
			<el-form v-if="isAdd" label-position="top">
				<h3>收款记录</h3>
				<div>
					<span>{{ `剩余金额：${order.arrears}` }}</span>
				</div>
				<h4>账单明细</h4>
				<el-button type="text" @click="applyPaymentShow">
					申请收款
				</el-button>
				<span v-if="order.status !== 1 && order.paymentFlowId === '0'" style="color: #E6A23C;">
					待审核
				</span>
				<el-table :data="billingList" border style="width: 100%" :max-height="400">
					<el-table-column prop="i" fixed="left" label="序号" width="50">
					</el-table-column>
					<el-table-column v-if="order.orderType === 2" label="本期" width="80">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.currentPeriod === -1" type="warning">
								定金
							</el-tag>
							<el-tag v-else-if="scope.row.currentPeriod === 0">
								首付
							</el-tag>
							<el-tag v-else-if="scope.row.currentPeriod > 0 && order.paymentMethod === 0">
								尾款
							</el-tag>
							<el-tag v-else-if="scope.row.currentPeriod > 0">
								{{ `第${scope.row.currentPeriod}期` }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="amount" label="收款金额" width="120">
					</el-table-column>
					<el-table-column prop="repaymentDate" label="收款日期" width="160">
					</el-table-column>
					<el-table-column prop="fundsReceived" label="实收金额" width="120">
					</el-table-column>
					<el-table-column prop="dateReceived" label="实收日期" width="160">
					</el-table-column>
					<el-table-column prop="account" label="收款账户" fit>
					</el-table-column>
					<el-table-column label="账单状态" width="100">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.billStatus === 0" type="warning">
								待收款
							</el-tag>
							<el-tag v-else-if="scope.row.billStatus === 1" type="success">
								已收款
							</el-tag>
							<el-tag v-if="scope.row.billStatus === 2" type="danger">
								已逾期
							</el-tag>
						</template>
					</el-table-column>
				</el-table>
			</el-form>
		</div>

		<!-- 申请收款 -->
		<el-dialog style="margin-top:0" :visible.sync="applicationShow" width="50%" title="收款申请"
			@close="applicationCloseDialog">
			<el-form inline label-position="top" class="payment" :model="billing" :rules="paymentRules"
				ref="paymentForm">
				<el-form-item v-if="order.orderType === 2 && order.paymentMethod > 0" label="总期数">
					<el-input :value="billing.totalPeriod" readonly>
					</el-input>
				</el-form-item>
				<el-form-item label="总金额">
					<el-input :value="order.transactionAmount" readonly>
					</el-input>
				</el-form-item>
				<el-form-item v-if="order.orderType === 2 && order.paymentMethod > 0" label="本期">
					<el-input v-if="billing.currentPeriod === -1" value="定金" readonly>
					</el-input>
					<el-input v-else-if="billing.currentPeriod === 0" value="首付款" readonly>
					</el-input>
					<el-input v-else :value="billing.currentPeriod" readonly>
					</el-input>
				</el-form-item>
				<el-form-item v-if="order.orderType === 2 && order.paymentMethod === 0" label="本期">
					<el-input v-if="billing.currentPeriod === -1" value="定金" readonly>
					</el-input>
					<el-input v-else-if="billing.currentPeriod === 0" value="首付款" readonly>
					</el-input>
					<el-input v-else value="尾款" readonly>
					</el-input>
				</el-form-item>
				<el-form-item label="收款金额">
					<el-input :value="billing.amount" readonly>
					</el-input>
				</el-form-item>
				<el-form-item label="实收金额" prop="fundsReceived">
					<el-input v-model="billing.fundsReceived" placeholder="输入实收金额" type="number" step="0.01"
						@input="chenkAmount">
					</el-input>
				</el-form-item>
				<el-form-item label="收款账户" prop="account">
					<el-select v-model="billing.account" filterable remote clearable placeholder="按账户搜索"
						style="width: 100%;" :loading="accountLoading" :remote-method="getAccountList"
						@focus="getAccountList('')">
						<el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<div>
					<el-button type="primary" @click="applyPayment" v-debounce>
						确定
					</el-button>
					<el-button @click="applicationCloseDialog">
						取消
					</el-button>
				</div>
			</el-form>
		</el-dialog>
		<input type="file" id="fileInput" ref="fileInput" style="display: none" @change="handleFileChange" />
	</div>
</template>

<script>
import config from '../../api/apiURL.js';
import uploadFile from '../../api/uploadFile.js';
import clientsApi from '../../api/clients.js';
import warehouseApi from '../../api/warehouse.js';
import orderApi from '../../api/order.js';
import userApi from '../../api/user.js';
import financeApi from '../../api/financeManage.js';
import docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import JSZipUtils from 'jszip-utils';
import {
	saveAs
} from 'file-saver';
import {
	randomString,
	numberToChinese
} from '../../utils/common.js';
import productType from '../../api/productType.js';
import productlibrary from '../../api/productlibrary.js';
export default {
	data() {
		return {
			userInfo: {}, // 登录用户
			isAdd: false, // true详情，false添加
			isReceipt: false, // 生成单据按钮是否显示
			loading: false, // 通用列表
			selectLoading: false, // 通用远程搜索加载动画
			clientsShow: false, // 控制选择客户弹窗显示
			clientForm: {
				name: null,
				type: null, // 客户类型
				isSalesman: 0, // 0客户列表，1公海池
				status: 0, // 查询已过审核
				currentPage: 1,
				pageSize: 50,
				total: 0,
			},
			clientList: [], // 客户列表
			devicesShow: false, // 控制选择产品弹窗显示
			form: {
				partName: null,
				isProduct: 0,
				warehouseType: void 0,
				currentPage: 1,
				pageSize: 50,
				total: 0,
			},
			devicesList: [], // 产品列表
			selectDevicesList: [], // 选择的产品列表
			userList: [], // 业务员列表
			afterSaleList: [], // 售后员列表
			accountList: [], // 账户列表
			applicationShow: false,
			orderId: null, // 订单id
			// 订单
			order: {
				id: null,
				sn: null, // 订单流水
				clientsId: null, // 客户id
				name: null, // 客户姓名
				company: null, // 客户公司
				phone: null, // 客户联系电话
				address: null, // 交货地址
				clientsIdCard: null, // 客户身份证号
				copyOfIdCard: null, // 客户身份证复印件url
				userId: null, // 业务员id
				nickName: null, // 业务员姓名
				deliveryTime: '', // 交货时间
				orderType: 1, // 订单类型（1开销开单，2签订合同）
				transactionAmount: null, // 总金额
				deposit: null, // 定金
				downPayment: null, // 首付款
				paymentMethod: 0, // 付款方式（0全款，1分一期，2分两期，3...）
				phaseAmount: null, // 每期应还
				lastAmount: null, // 末期应还
				paymentType: 0, // 付款类型（0先发后付，1先付后发）
				receipt: null, // 验收单url
				logisticsInformation: null, // 物流信息url
				contract: null, // 签订合同url
				afterSaleId: null, // 售后员id
				afterSaleName: null, // 售后姓名
				place: '', // 签订地点
				deadline: '', // 还款截止日期
				goodsList: [], // 产品列表
				remark: null, // 备注
			},
			balancePayment: null, // 尾款
			billingList: [], // 账单列表
			billing: {
				fundsReceived: null,
				account: null,
			},
			byStages: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], // 分期
			READ_IMG_URL: config.READ_IMG_URL,
			copyOfIdCardList: [], // 身份证复印件url
			copyOfIdCardShowList: [],
			receiptList: [], // 验收单url
			receiptShowList: [],
			logisticsInformationList: [], // 物流信息url
			logisticsInformationShowList: [],
			contractList: [], // 签订合同url
			contractShowList: [],
			selectedFile: '', // 选择上传的文件
			imgType: '', // 上传图片类型（0身份证图片，1验收单，2物流信息，3签订合同）
			imgUrl: '',
			// 验证规则
			rules: {
				clientsId: [{
					required: true,
					message: '请选择下单客户',
					trigger: 'change'
				}],
				clientsIdCard: [{
					required: true,
					message: '请填写客户身份证号码',
					trigger: 'blur'
				}, {
					pattern: /(^\d{17}[\dXx]$)/,
					message: '请输入正确的身份证号码格式',
					trigger: 'blur'
				}],
				deliveryTime: [{
					required: true,
					message: '请选择日期',
					trigger: 'blur'
				}],
				deposit: [{
					required: true,
					message: '请输入定金',
					trigger: 'blur'
				}],
				downPayment: [{
					required: true,
					message: '请输入首付款',
					trigger: 'blur'
				}],
				place: [{
					required: true,
					message: '请输入地址',
					trigger: 'blur'
				}],
				deadline: [{
					required: true,
					message: '请选择日期',
					trigger: 'blur'
				}],
				userId: [{
					required: true,
					message: '请选择业务员',
					trigger: 'blur'
				}]
			},
			accountLoading: false,
			paymentRules: {
				fundsReceived: [{
					required: true,
					validator: this.validate,
					trigger: 'blur'
				}],
				account: [{
					required: true,
					message: '请选择收款账户',
					trigger: 'blur'
				}]
			},
			productTypeList: new Array(),
			productlibraryList: new Array()
		}
	},
	created() {
		this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
		this.userInfo.roleId = parseInt(this.userInfo.roleId)
		// 从本地存储获取订单id
		this.orderId = localStorage.getItem("orderId")
		// 判断是详情还是添加
		if (this.orderId) {
			this.getOrder();
		}
		// 初始化图片
		const url = "https://kris-k.oss-cn-hangzhou.aliyuncs.com/kris/c179093a-41b0-4c70-bc1f-6e5973f35c98-jia.png"
		this.imgUrl = url;
		// this.copyOfIdCardUrl = url;
		// this.receiptUrl = url;
		// this.logisticsInformationUrl = url;
		// this.contractUrl = url;
	},
	destroyed() {
		// 销毁页面时移除本地存储的订单id
		localStorage.removeItem("orderId")
	},
	mounted() {
		this.getProductTypeList()
		this.getProductlibraryList()
	},
	computed: {
		typeListComputed() {
			return this.form.warehouseType ?
				this.productTypeList.filter(
					value => this.productlibraryList.find(
						i => i.id == this.form.warehouseType
					).producttype.split(',').findIndex(item => item == value.id) != -1
				) : this.productTypeList
		}
	},
	methods: {
		validate(rule, value, callback) {
			//console.log("value=>", value)
			if (value === '' || value === null) {
				callback(new Error('请输入实收金额'));
			} else if (value > this.order.arrears) {
				callback(new Error('收款金额不能大于剩余金额'));
			} else if (value === 0 && this.order.transactionAmount !== 0) {
				callback(new Error('收款金额不能为0'));
			} else if (this.order.orderType === 1 && value !== this.billing.amount) {
				callback(new Error('开销开单只能支付全款'));
			} else if (this.billing.currentPeriod === this.billing.totalPeriod &&
				value !== this.order.arrears) {
				callback(new Error('已是最后一期，请付清剩余金额'));
			} else {
				callback();
			}
		},
		// 返回上个页面
		toBack() {
			this.$router.push({
				path: "/order/orderList"
			})
		},
		// 业务员与管理员显示生成合同按钮
		generateContract() {
			if (this.userInfo.roleId < 4 && this.orderId !== null) {
				return true;
			}
			return false;
		},
		// 获取订单详情
		getOrder() {
			const loading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			const data = {
				id: this.orderId
			}
			orderApi.getOrder(data).then(res => {
				if (res.code === 200) {
					this.order = res.data;
					this.balancePayment = this.order.balancePayment;
					// 判断是否通过订单审核
					if (this.order.orderFlowId == '1') {
						// 订单通过审核锁定不可修改
						this.isAdd = true;
					}
					if (this.order.userId !== null) {
						const data = {
							id: this.order.userId,
							nickName: this.order.nickName
						}
						this.userList.push(data);
					}
					if (this.order.afterSaleId !== null) {
						const data = {
							id: this.order.afterSaleId,
							nickName: this.order.afterSaleName
						}
						this.afterSaleList.push(data);
					}
					this.getOrderBillingList();
					if (this.order.copyOfIdCardList !== null) {
						this.copyOfIdCardList = this.order.copyOfIdCardList;
						this.copyOfIdCardList.forEach(item => {
							this.copyOfIdCardShowList.push(this.READ_IMG_URL + item);
						})
					}
					//console.log("copyOfIdCardShowList====>",this.copyOfIdCardShowList)
					if (this.order.receiptList !== null) {
						this.receiptList = this.order.receiptList;
						this.receiptList.forEach(item => {
							this.receiptShowList.push(this.READ_IMG_URL + item);
						})
					}
					//console.log("receiptShowList====>",this.receiptShowList)
					if (this.order.logisticsInformationList !== null) {
						this.logisticsInformationList = this.order.logisticsInformationList;
						this.logisticsInformationList.forEach(item => {
							this.logisticsInformationShowList.push(this.READ_IMG_URL + item);
						})
					}
					//console.log("logisticsInformationShowList====>",this.logisticsInformationShowList)
					if (this.order.contractList !== null) {
						this.contractList = this.order.contractList;
						this.contractList.forEach(item => {
							this.contractShowList.push(this.READ_IMG_URL + item);
						})
					}
					//console.log("contractShowList====>",this.contractShowList)
					// 业务员与管理员显示生成单据按钮
					if (this.userInfo.roleId < 4 && this.orderId !== null && this.order.orderType === 1) {
						this.isReceipt = true;
					}
					this.order.goodsList = res.data.goodsList.map((item, index) => {
						let data = {
							i: index + 1,
							goodsId: item.goodsId,
							image: item.image,
							partName: item.partName,
							isProduct: item.isProduct,
							model: item.model,
							price: item.price, // 销售单价
							goodsCount: item.goodsCount, // 卖出数量
							totalAmount: item.totalAmount, // 总计金额
							count: item.count, // 库存
							devicesDescribe: item.devicesDescribe,
							remark: item.remark,
							inventory: false, // 库存不足
						}
						return data;
					})
				}
			}).finally(() => {
				loading.close();
			})
		},
		// 选择订单类型
		orderTypeChange(e) {
			// console.log("e=>",e)
			this.restData();
			this.$refs.ruleForm.resetFields();
			this.order.orderType = e
		},
		// 打开选择客户弹窗
		clientsDialogShow() {
			this.clientsShow = true;
			this.getClientList();
		},
		// 获取客户列表
		getClientList() {
			this.loading = true;
			clientsApi.getClientsList(this.clientForm).then(res => {
				if (res.code === 200) {
					this.clientForm.total = res.data.total;
					this.clientList = res.data.clientsVoList.map((item, index) => {
						item.i = (this.clientForm.currentPage - 1) * this.clientForm.pageSize + index + 1
						return item;
					})
				}
			}).finally(() => {
				this.loading = false;
			})
		},
		// 客户列表页码变化
		clientFormCurrentChange(currentPage) {
			this.clientForm.currentPage = currentPage;
			this.getClientList();
		},
		// 客户列表页码条数变化
		clientFormSizeChange(pageSize) {
			this.clientForm.pageSize = pageSize;
			this.getClientList();
		},
		// 选择客户
		selectClientChange(item) {
			this.order.clientsId = item.id;
			this.order.name = item.name;
			this.order.company = item.company;
			this.order.phone = item.phone;
			let address = item.province + item.city + item.district + item.address;
			this.order.address = address;
			this.clientsShow = false;
		},
		// 打开选择产品弹窗
		devicesDialogShow() {
			this.devicesShow = true;
			this.getDevicesList();
		},
		// 获取产品列表
		getDevicesList() {
			this.loading = true;
			warehouseApi.getDeviceList(this.form).then(res => {
				if (res.code === 200) {
					this.form.total = res.data.total
					this.devicesList = res.data.devicesList.map((item, index) => {
						item.i = (this.form.currentPage - 1) * this.form.pageSize + index + 1;
						return item;
					})
					// 显示已选择的
					this.$refs.multipleTable.clearSelection();
					if (this.order.goodsList.length > 0) {
						this.devicesList.forEach(row => {
							this.order.goodsList.forEach(part => {
								if (part.goodsId === row.id) {
									this.$refs.multipleTable.toggleRowSelection(row, true);
								}
							})
						})
					}
				}
			}).finally(() => {
				this.loading = false;
			})
		},
		// 页码变化
		formCurrentChange(currentPage) {
			this.form.currentPage = currentPage;
			this.getDevicesList();
		},
		// 页码条数变化
		formSizeChange(pageSize) {
			this.form.pageSize = pageSize;
			this.getDevicesList();
		},
		// 多选产品
		handleSelectionChange(e) {
			this.selectDevicesList = e;
		},
		// 确认选择
		confirmParts() {
			for (var i = 0; i < this.selectDevicesList.length; i++) {
				var devices = this.selectDevicesList[i];
				if (this.order.goodsList.length > 0) {
					let flog = false;
					for (var j = 0; j < this.order.goodsList.length; j++) {
						var part = this.order.goodsList[j];
						if (part.goodsId === devices.id) {
							flog = true;
							break;
						}
					}
					if (flog) {
						continue;
					}
				}
				let data = {
					goodsId: devices.id,
					image: devices.image,
					partName: devices.partName,
					model: devices.model,
					isProduct: devices.isProduct,
					price: devices.price, // 销售单价
					goodsCount: 1, // 卖出数量
					totalAmount: devices.price, // 总计金额
					count: devices.count, // 库存
					devicesDescribe: devices.devicesDescribe,
					remark: devices.remark,
					inventory: false, // 库存不足
				}
				this.order.goodsList.push(data);
				this.computeAmount();
			}
			let newList = this.order.goodsList.map((item, index) => {
				item.i = index + 1;
				return item;
			})
			this.order.goodsList = newList;
			this.devicesShow = false;
		},
		// 删除产品
		deleteParts(item) {
			let newList = this.order.goodsList.filter(part => part.goodsId !== item.goodsId)
			this.order.goodsList = newList.map((part, index) => {
				part.i = index + 1;
				return part;
			})
			if (this.$refs.multipleTable !== null) {
				this.devicesList.forEach(row => {
					if (item.goodsId === row.id) {
						this.$refs.multipleTable.toggleRowSelection(row, false);
					}
				})
			}
			this.computeAmount();
		},
		// 日期转换
		dateChange(event, type) {
			// console.log("event=>",event)
			// console.log("type=>",type)
			// 获取年、月、日
			let year = event.getFullYear();
			let month = event.getMonth() + 1; // 月份从0开始，需要加1
			if (month < 10) {
				month = '0' + month; // 如果月份小于10，在前面补0
			}
			let day = event.getDate();
			if (day < 10) {
				day = '0' + day; // 如果日期小于10，在前面补0
			}
			// 构建目标日期格式
			let targetDateString = `${year}-${month}-${day}`;
			if (type === 'deliveryTime') {
				this.order.deliveryTime = targetDateString;
			} else {
				this.order.deadline = targetDateString;
			}

		},
		// 数量输入检查，计算库存
		inputCheck(e, row) {
			let inputNumber = row.goodsCount
			if (inputNumber <= 0) {
				inputNumber = 1
			}
			let value = parseFloat(inputNumber)
			if (isNaN(value)) {
				value = 1;
			}

			// 计算库存
			if (row.count - row.goodsCount < 0) {
				row.inventory = true;
			} else {
				row.inventory = false;
			}
			row.goodsCount = value
		},
		// 检查数字，小于0.00，或者超过小数点后两位返回null
		checkNumber(value) {
			if (value < 0.00) {
				value = null;
			}
			// 使用正则表达式匹配小数点后两位以内的数字或整数
			let regex = /^\d+(\.\d{1,2})?$/;
			if (!regex.test(value)) {
				value = null
			}
			return value;
		},
		// 检查输入的总金额
		check(value) {
			let inputNumber = parseFloat(this.order.transactionAmount);
			inputNumber = this.checkNumber(inputNumber);
			this.order.transactionAmount = inputNumber
		},
		// 计算单个产品总计
		countChange(e, row) {
			row.totalAmount = (row.goodsCount * row.price).toFixed(2)
			this.computeAmount();
		},
		// 计算总金额
		computeAmount() {
			if (this.order.goodsList.length > 0) {
				let Amount = 0.00
				this.order.goodsList.forEach(item => {
					Amount = Amount + item.totalAmount
				})
				this.order.transactionAmount = Amount;
				// 检查定金
				this.depositCheck();
				// 计算尾款
				this.depositChange();
			}
		},
		// 输入总金额后
		change(e) {
			// 检查输入的定金
			this.depositCheck()
			// 计算尾款
			this.depositChange()
		},
		// 检查输入的定金
		depositCheck(value) {
			if (this.order.orderType === 1) {
				return;
			}
			let inputNumber = parseFloat(this.order.deposit);
			inputNumber = this.checkNumber(inputNumber)
			// 定金不能等于或超过总金额 
			if (this.order.transactionAmount !== null && this.order.transactionAmount !== 0) {
				if (inputNumber >= this.order.transactionAmount) {
					inputNumber = null
					this.$message.warning("定金不能等于或超过总金额")
				}
			}
			this.order.deposit = inputNumber
			// 检查输入的首付款
			this.downPaymentCheck();
		},
		// 检查输入的首付款
		downPaymentCheck(value) {
			if (this.order.orderType === 1) {
				return;
			}
			let inputNumber = parseFloat(this.order.downPayment);
			inputNumber = this.checkNumber(inputNumber)
			// 首付款不能超过总金额
			if (this.order.transactionAmount !== null) {
				if (inputNumber > this.order.transactionAmount) {
					inputNumber = null
					this.$message.warning("首付款不能超过总金额")
				}
			}
			// 首付款不能超过总金额-定金
			if (this.order.transactionAmount !== null && this.order.deposit !== null) {
				if (inputNumber > this.order.transactionAmount - this.order.deposit) {
					inputNumber = null
					this.$message.warning("首付款不能超过总金额减去定金")
				}
			}
			this.order.downPayment = inputNumber
		},
		// 计算尾款，总金额-定金-首付款
		depositChange(e) {
			if (this.order.orderType === 1) {
				return;
			}
			if (!this.isAdd) {
				//console.log("输入的定金=>",e)
				if (this.order.transactionAmount > 0.00 &&
					this.order.deposit > 0.00 &&
					this.order.downPayment > 0.00) {
					this.balancePayment = (this.order.transactionAmount - this.order.deposit - this.order.downPayment)
						.toFixed(2)
					if (this.balancePayment <= 0.00) {
						this.order.deposit = null
						this.order.downPayment = null
						this.balancePayment = null
						this.order.phaseAmount = null
						this.order.lastAmount = null
						this.$message.warning("尾款为0！")
					}
				}
				this.paymentMethodChange();
			}
		},
		// 计算每期应还和末期应还
		paymentMethodChange(e) {
			if (this.order.orderType === 1) {
				return;
			}
			// console.log("e=>", e)
			if (this.order.paymentMethod === 0) {
				return;
			}
			if (this.balancePayment === null) {
				return
			}
			// 计算每期，尾款除以期数
			this.order.phaseAmount = parseInt((this.balancePayment / this.order.paymentMethod).toFixed(2))
			// 计算末期
			const deficiency = parseFloat(this.balancePayment - (this.order.phaseAmount * this.order.paymentMethod))
			this.order.lastAmount = parseFloat((this.order.phaseAmount + deficiency).toFixed(2))
		},
		// 点击上传图片
		selectFile(type) {
			this.imgType = type;
			this.$refs.fileInput.click();
		},
		// 选择文件
		handleFileChange(event) {
			this.selectedFile = event.target.files[0];
			// 上传前验证
			const fileSuffix = this.selectedFile.name.substring(this.selectedFile.name.lastIndexOf(".") + 1);
			const whiteList = ["jpg", "jpeg", "png", "JPG", "JPEG", "PNG"];
			if (whiteList.indexOf(fileSuffix) === -1) {
				this.$message.error("上传文件只能是 jpg、png格式！");
				return;
			}
			const isLt5M = this.selectedFile.size / 1024 / 1024 < 5;
			if (!isLt5M) {
				this.$message.error('上传的图片大小不能超过5MB!');
				return;
			}
			this.uploadImage();
		},
		//发送上传文件api
		uploadImage() {
			const loading = this.$loading({
				lock: true,
				text: '上传中...',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			let formData = new FormData();
			formData.append("file", this.selectedFile);
			uploadFile.uploadImage(formData).then(res => {
				if (res.code === 200) {
					const url = res.data
					if (this.imgType === 0) {
						this.copyOfIdCardList.push(url);
						this.copyOfIdCardShowList.push(this.READ_IMG_URL + url);
						this.order.copyOfIdCard = this.copyOfIdCardList.join(";");
					} else
						if (this.imgType === 1) {
							this.receiptList.push(url);
							this.receiptShowList.push(this.READ_IMG_URL + url);
							this.order.receipt = this.receiptList.join(";");
						} else if (this.imgType === 2) {
							this.logisticsInformationList.push(url);
							this.logisticsInformationShowList.push(this.READ_IMG_URL + url);
							this.order.logisticsInformation = this.logisticsInformationList.join(";");
						} else {
							this.contractList.push(url);
							this.contractShowList.push(this.READ_IMG_URL + url);
							this.order.contract = this.contractList.join(";");
						}
					if (this.isAdd) {
						orderApi.orderDelivery(this.order).then(res => {
							if (res.code === 200) {
								this.$message.success("上传成功")
							}
						}).finally(() => {
							loading.close();
						});
					}
				}
			}).finally(() => {
				this.selectedFile = '';
				loading.close();
			})
			// UploadFile(formData).then((data) => {
			// 	let url = data.data;

			// }).catch(() =>{
			// 	this.$message.success("上传失败");
			// 	loading.close();
			// });
		},
		// 删除图片
		deleteImg(type, index) {
			if (this.isAdd) {
				this.$confirm('是否要删除此图片？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					// 用户点击了确定按钮时执行的操作
					this.doDeleteImg(type, index);
				}).catch(() => {
					// 用户点击了取消按钮时执行的操作，或者点击遮罩层关闭对话框时触发的事件

				});
			} else {
				this.doDeleteImg(type, index);
			}
		},
		doDeleteImg(type, index) {
			if (type === 0) {
				this.copyOfIdCardList.splice(index, 1);
				if (this.copyOfIdCardList.length > 0) {
					this.order.copyOfIdCard = this.copyOfIdCardList.join(";");
				} else {
					this.order.copyOfIdCard = ''
				}
				this.copyOfIdCardShowList = [];
				this.copyOfIdCardList.forEach(item => {
					this.copyOfIdCardShowList.push(this.READ_IMG_URL + item);
				})
			}
			if (type === 1) {
				this.receiptList.splice(index, 1);
				if (this.receiptList.length > 0) {
					this.order.receipt = this.receiptList.join(";")
				} else {
					this.order.receipt = ''
				}
				this.receiptShowList = [];
				this.receiptList.forEach(item => {
					this.receiptShowList.push(this.READ_IMG_URL + item);
				})
			}
			if (type === 2) {
				this.logisticsInformationList.splice(index, 1);
				if (this.logisticsInformationList.length > 0) {
					this.order.logisticsInformation = this.logisticsInformationList.join(";")
				} else {
					this.order.logisticsInformation = ''
				}
				this.logisticsInformationShowList = []
				this.logisticsInformationList.forEach(item => {
					this.logisticsInformationShowList.push(this.READ_IMG_URL + item);
				})
			}
			if (type === 3) {
				this.contractList.splice(index, 1);
				if (this.contractList.length > 0) {
					this.order.contract = this.contractList.join(";")
				} else {
					this.order.contract = ''
				}
				this.contractShowList = []
				this.contractList.forEach(item => {
					this.contractShowList.push(this.READ_IMG_URL + item);
				})
			}
			if (this.isAdd) {
				const loading = this.$loading({
					lock: true,
					text: '请求中...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				orderApi.orderDelivery(this.order).then(res => {
					if (res.code === 200) {
						this.$message.success("删除成功")
					}
				}).finally(() => {
					loading.close();
				})
			}
		},
		// 提交
		submitForm(formName) {
			console.log("提交的数据===>", this.order);
			let _this = this
			this.$refs[formName].validate((valid) => {
				if (!valid) {
					_this.$message.error("请将订单填写完整!")
					return false;
				}
				if (this.order.goodsList.length < 1) {
					_this.$message.error("请选择产品!")
					return false;
				}
				_this.$confirm('是否提交订单？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					if (_this.orderId) {
						// 有id为修改订单
						_this.order.id = _this.orderId;
						orderApi.updateOrder(_this.order).then(res => {
							if (res.code === 200) {
								_this.$message.success("提交成功")
								_this.toBack();
							}
						})
					} else {
						// 添加
						orderApi.addOrder(_this.order).then(res => {
							if (res.code === 200) {
								_this.$message.success("提交成功")
								_this.toBack();
							}
						})
					}
				})
			});
		},
		// 重置
		resetForm(formName) {
			console.log("===>", this.$refs[formName])
			this.$refs[formName].resetFields();
			this.restData();
		},
		// 获取订单账单
		getOrderBillingList() {
			this.billingList = []
			if (!this.isAdd) {
				return;
			}
			const data = {
				orderId: this.order.id
			}
			orderApi.getOrderBillingList(data).then(res => {
				if (res.code === 200) {
					this.billingList = res.data.map((item, index) => {
						item.i = index + 1;
						return item;
					})
				}
			})
		},
		// 申请收款按钮
		// paymentButton() {
		// 	//console.log(this.userInfo)
		// 	if (this.order.status !== 1 && this.userInfo.roleId < 4) {
		// 		if (this.order.paymentFlowId === null) {
		// 			return true;
		// 		} else if (this.order.paymentFlowId === '2') {
		// 			return true;
		// 		}
		// 	}
		// 	return false;
		// },
		// 申请收款
		applyPaymentShow() {
			this.getOrderBilling();
			this.applicationShow = true;
		},
		// 获取首个待还款的订单账单
		getOrderBilling() {
			const data = {
				orderId: this.order.id,
				billStatus: 3
			}
			orderApi.getOrderBillingList(data).then(res => {
				if (res.code === 200) {
					//console.log("列表=>",res.data)
					if (res.data.length > 0) {
						this.billing = res.data[0];
						const data = {
							account: res.data[0].account,
							id: res.data[0].accountId
						}
						this.accountList = []
						this.accountList.push(data)
						this.billing.account = data.id;
					}
				}
			})
		},
		// 检查输入的实收金额
		chenkAmount(e) {
			let inputNumber = parseFloat(this.billing.fundsReceived);
			inputNumber = this.checkNumber(inputNumber);
			this.billing.fundsReceived = inputNumber;
		},
		// 关闭收款申请
		applicationCloseDialog() {
			this.billing = {};
			this.applicationShow = false;
		},
		// 确定申请收款
		applyPayment() {
			this.$refs.paymentForm.validate((valid) => {
				if (valid) {
					const data = {
						id: this.billing.id,
						fundsReceived: this.billing.fundsReceived,
						account: this.billing.account
					}
					orderApi.application(data).then(res => {
						if (res.code === 200) {
							this.$message.success("申请成功")
							this.applicationCloseDialog();
							this.getOrder();
						}
					})
				}
			});
		},
		// 获取业务员，售后员
		getUser(type) {
			// if (!this.isAdd) {
			// 	return;
			// }
			let data = {}
			if (type === 3) {
				data.id = this.order.userId
			} else {
				data.id = this.order.afterSaleId
			}
			if (data.id === null || data.id === '') {
				return;
			}
			userApi.getUserWithDelete(data).then(res => {
				if (res.code === 200) {
					if (type === 3) {
						this.userList.push(res.data)
					} else {
						this.afterSaleList.push(res.data)
					}
				}
			})
		},
		// 选择业务员框是否隐藏
		salesmanShow() {
			if (this.order.orderFlowId === '1' || this.userInfo.roleId === 1) {
				return true;
			}
			return false;
		},
		// 远程搜索业务员
		async getUserList(query) {
			this.selectLoading = true;
			let data = {
				nickName: query,
				roleId: 3,
			}
			let roleId3 = await userApi.fuzzyQuery(data)
			data.roleId = 1
			let roleId1 = await userApi.fuzzyQuery(data)
			data.roleId = 7
			let roleId7 = await userApi.fuzzyQuery(data)
			this.userList = [...roleId1.data.userVoList, ...roleId3.data.userVoList, ...roleId7.data.userVoList]
			this.selectLoading = false;
		},
		// 能否修改业务员
		userDisabled() {
			if (this.userInfo.roleId < 3) {
				return false;
			}
			return true;
		},
		// 确定业务员
		selectUserChange(e) {
			console.log("===>", this.order.id)
			if (this.order.id !== null) {
				const data = {
					id: this.order.id,
					userId: e
				}
				orderApi.changeSalesman(data).then(res => {
					if (res.code === 200) {
						this.$message.success("修改成功")
					}
				})
			} else {
				this.order.userId = e
			}
		},
		// 能否修改售后员
		afterSaleDisabled() {
			if (this.userInfo.roleId < 4) {
				return false;
			}
			return true;
		},
		// 远程搜索售后员
		getAfterSaleList(query) {
			this.selectLoading = true;
			const data = {
				nickName: query,
				roleId: 7,
			}
			userApi.fuzzyQuery(data).then(res => {
				if (res.code === 200) {
					this.afterSaleList = res.data.userVoList.map(item => {
						item.label = `${item.nickName}(${item.empno})`
						return item;
					})
					this.selectLoading = false;
				}
			})
		},
		// 确定售后员
		selectAfterSaleChange(e) {
			if (this.order.id !== null) {
				const data = {
					id: this.order.id,
					afterSaleId: e
				}
				orderApi.changeAfterSale(data).then(res => {
					if (res.code === 200) {
						this.$message.success("修改成功")
					}
				})
			} else {
				this.order.afterSaleId = e
			}
		},
		// 生成合同
		generate() {
			// 读取并获得模板文件的二进制内容
			let filePath = '';
			let fileName = '';
			if (this.order.orderType === 1) {
				filePath = "expenditure.docx";
				fileName = this.order.company + "开销合同.docx";
			} else {
				filePath = "contract.docx";
				fileName = this.order.company + "签订合同.docx";
			}
			JSZipUtils.getBinaryContent(filePath, (error, content) => {
				// model.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
				// 抛出异常
				if (error) {
					throw error;
				}
				// 创建一个PizZip实例，内容为模板的内容
				let zip = new PizZip(content);
				// 创建并加载docxtemplater实例对象
				let doc = new docxtemplater().loadZip(zip);
				// 准备填充的数据
				let data = {}
				var nowDate = new Date();
				var year = nowDate.getFullYear();
				var month = nowDate.getMonth() + 1;
				var day = nowDate.getDate();
				const date = `${year}/${month}/${day}`
				const random = randomString(2);
				const sn = `${year}${month}${day}${random}`
				if (this.order.orderType === 1) {
					// 开销合同
					let paymentType = "";
					if (this.order.paymentType === 0) {
						paymentType = "先发后付";
					} else {
						paymentType = "先付后发";
					}
					data = {
						company: this.order.company, // 客户公司名称
						nickName: this.order.nickName, // 业务员名称
						transactionAmount: this.order.transactionAmount, // 总金额
						phone: this.order.phone, // 客户电话
						address: this.order.address, // 客户地址
						date: date, // 日期
						paymentType: paymentType,
						goodsList: this.order.goodsList
					}
				} else {
					// 签订合同
					const depositZH = numberToChinese(this.order.deposit);
					const balancePaymentZH = numberToChinese(this.order.balancePayment);
					const downPaymentZH = numberToChinese(this.order.downPayment);
					const timeList = this.order.deadline.split("-");
					if (this.order.phaseAmount === null) {
						this.order.phaseAmount = 0
					}
					data = {
						sn: sn,
						company: this.order.company, // 客户公司名称
						goodsList: this.order.goodsList, // 产品列表
						transactionAmount: this.order.transactionAmount, // 总金额
						deposit: this.order.deposit, // 定金
						depositZH: depositZH,
						downPayment: this.order.downPayment, // 首付款
						downPaymentZH: downPaymentZH,
						paymentMethod: this.order.paymentMethod, // 分期数
						phaseAmount: this.order.phaseAmount, // 每期应还
						balancePayment: this.order.balancePayment, // 尾款
						balancePaymentZH: balancePaymentZH,
						name: this.order.name, // 客户名称
						phone: this.order.phone, // 客户手机号
						address: this.order.address, // 客户地址
						clientsIdCard: this.order.clientsIdCard, // 客户身份证号
						place: this.order.place, // 签订地点
						deadline: `${timeList[0]}年${timeList[1]}月${timeList[2]}日`, // 还款截止日期
					}
				}
				//console.log("data=>",data)

				// 设置模板变量的值
				doc.setData(data);
				try {
					// 用模板变量的值替换所有模板变量
					doc.render();
				} catch (error) {
					// 抛出异常
					let e = {
						message: error.message,
						name: error.name,
						stack: error.stack,
						properties: error.properties
					};
					console.log(JSON.stringify({
						error: e
					}));
					throw error;
				}

				// 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
				let out = doc.getZip().generate({
					type: "blob",
					mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
				});
				// 将目标文件对象保存为目标类型的文件，并命名
				saveAs(out, fileName);
			});
		},
		// 生成销售开单
		receipt() {
			// 读取并获得模板文件的二进制内容
			let filePath = 'receipt.docx';
			let fileName = this.order.company + "开销单据.docx";
			JSZipUtils.getBinaryContent(filePath, (error, content) => {
				// model.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
				// 抛出异常
				if (error) {
					throw error;
				}
				// 创建一个PizZip实例，内容为模板的内容
				let zip = new PizZip(content);
				// 创建并加载docxtemplater实例对象
				let doc = new docxtemplater().loadZip(zip);
				// 准备填充的数据
				let data = {}
				var nowDate = new Date();
				var year = nowDate.getFullYear();
				var month = nowDate.getMonth() + 1;
				var day = nowDate.getDate();
				const date = `${year}/${month}/${day}`
				const random = randomString(2);
				const sn = `${year}${month}${day}${random}`
				data = {
					company: this.order.company, // 客户公司名称
					nickName: this.order.nickName, // 业务员名称
					transactionAmount: this.order.transactionAmount, // 总金额
					phone: this.order.phone, // 客户电话
					address: this.order.address, // 客户地址
					date: date,// 日期
					goodsList: this.order.goodsList, // 产品列表
				}
				//console.log("data=>",data)

				// 设置模板变量的值
				doc.setData(data);
				try {
					// 用模板变量的值替换所有模板变量
					doc.render();
				} catch (error) {
					// 抛出异常
					let e = {
						message: error.message,
						name: error.name,
						stack: error.stack,
						properties: error.properties
					};
					console.log(JSON.stringify({
						error: e
					}));
					throw error;
				}

				// 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
				let out = doc.getZip().generate({
					type: "blob",
					mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
				});
				// 将目标文件对象保存为目标类型的文件，并命名
				saveAs(out, fileName);
			});
		},
		// 重置
		restData() {
			this.order = {
				id: this.orderId,
				sn: null, // 订单流水
				clientsId: null, // 客户id
				name: null, // 客户姓名
				company: null, // 客户公司
				phone: null, // 客户联系电话
				address: null, // 交货地址
				clientsIdCard: null, // 客户身份证号
				copyOfIdCard: null, // 客户身份证复印件url
				userId: null, // 业务员id
				nickName: null, // 业务员姓名
				deliveryTime: '', // 交货时间
				orderType: 1, // 订单类型（1开销开单，2签订合同）
				transactionAmount: null, // 总金额
				deposit: null, // 定金
				downPayment: null, // 首付款
				paymentMethod: 0, // 付款方式（0全款，1分一期，2分两期，3...）
				phaseAmount: null, // 每期应还
				lastAmount: null, // 末期应还
				paymentType: 0, // 付款类型（0先发后付，1先付后发）
				receipt: null, // 验收单url
				logisticsInformation: null, // 物流信息url
				contract: null, // 签订合同url
				afterSaleId: null, // 售后员id
				afterSaleName: null, // 售后姓名
				place: '', // 签订地点
				deadline: '', // 还款截止日期
				goodsList: [] // 产品列表
			}
			if (this.$refs.multipleTable) {
				this.$refs.multipleTable.clearSelection();
			}
		},
		//用户状态显示转换   0成交客户，1意向客户，2潜在客户，3失信客户
		typeInfo(data) {
			let typeVal = "";
			if (data == 0) {
				typeVal = "成交客户";
			} else if (data == 1) {
				typeVal = "意向客户";
			} else if (data == 2) {
				typeVal = "潜在客户";
			} else if (data == 3) {
				typeVal = "失信客户";
			}
			return typeVal;
		},
		// 远程搜索账户
		getAccountList(query) {
			this.accountLoading = true;
			const data = {
				accountName: query,
				currentPage: 1,
				pageSize: 10,
			}
			financeApi.getAccountList(data).then(res => {
				if (res.code === 200) {
					this.accountList = res.data.accountList
				}
			}).finally(() => {
				this.accountLoading = false;
			})
		},
		getProductTypeList() {
			productType.getProductType().then(res => {
				this.productTypeList = res.data
			})
		},
		getProductlibraryList() {
			productlibrary.getProductlibrary().then(res => {
				this.productlibraryList = res.data
			})
		}
	}
}
</script>

<style>
.el-form--inline .el-form-item {
	width: 520px;
	margin-right: 20px;
}

.el-select {
	width: 100%;
}

.htimg {
	width: 150px;
	height: 150px;
	object-fit: cover;
	/* 保持原始宽高比，填充容器 */
}

.order-img-div {
	width: 150px;
	height: 150px;
}

.order-img-div:hover .hover-icon {
	display: block;
}

.hover-icon {
	display: none;
	font-size: 24px;
	position: absolute;
	top: 0;
	right: 0;
	color: #ffffff;
	background-color: black;
	opacity: 0.9
}

.hover-icon:hover {
	cursor: pointer;
}
</style>